package com.mango.community.controller.interceptor;

import com.mango.community.annotation.LoginRequired;
import com.mango.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/25 22:59
 * 自定义注解的拦截器
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断拦截对象是不是一个方法
        if (handler instanceof HandlerMethod){
            //将handler 转为HandlerMethod
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取他拦截到的method对象
            Method method = handlerMethod.getMethod();
            //在这个方法上按照注解的类型拿到这个注解
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
            //拿到的注解不是空的（在这个方法上存在这个注解）并且用户是空的时候 return false 拒绝后续的请求
            if (loginRequired != null && hostHolder.getUser() == null ){
                //拒绝请求并且重定向到登录页面
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
